import axios from 'axios'
import {showToast} from 'vant'
import {getToken, removeToken, storage, TOKEN_DATA, TOKEN_PRE} from "@/utils/storage";
import router from "@/routers";

const SUCCESS_CODE = "200"
const BASE_URL = "/api"

const instance = axios.create({
    baseURL: BASE_URL,
    timeout: 60000,
    headers: {
        'Content-type': 'application/json',
        // token: $pathUtils.getQueryString('token'),
        // token: "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNTYyOTA3MTk4IiwiZXhwIjoxNjgxNTU0ODM1fQ.ECU_CpwcFfZErEAttEJkogNWiLIvIQRIEr5b05oDDBGEY02ZomplEsqe_DaF3-3kF_5rtqRSH_hEGCEcI76Lqg",
        // 'Access-Control-Allow-Headers': 'Content-Type,Authorization',
        // 'Authorization':getToken(),
        'Authorization': getToken()
    },
    // withCredentials: true
})

instance.interceptors.request.use(config => {
    console.log(config)
    if (config.url === "/login/web_token") {
        config.headers.Authorization = "basic amgxMjMzMjExMjM0NTY3OmpoMTIzMzIxMTIzNDU2Nw=="
    }
    return config
}, err => Promise.reject(err))

instance.interceptors.response.use((res) => {
    if (res.data.code === SUCCESS_CODE) {
        return Promise.resolve(res.data.data)
    }
    if (res.data.code === "401") {
        // 跳转到登录界面
        // window.location.href = '/login';
        // removeToken()
        router.push('/login')
    }
    return Promise.reject(res.data)
}, (err) => {
    const errStr = err.message || err.toString()
    showToast(errStr)
    return Promise.reject(err)
})

export default {
    request(url, data, method, config) {
        return instance.request({
            url,
            data,
            method,
            ...config
        })
    },
    post(url, data, config) {
        return this.request(url, data, 'POST', config)
    },
    get(url, data, config) {
        return this.request(url, data, 'GET', config)
    }
}
